#include "acceptor.h"
#include "logger.h"

#include <sys/socket.h>

static int createNonBlockingSocket(){
    int sockfd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP);
    if(sockfd < 0){
        LOG_FATAL("%s:%s:%d create nonblocking socket fail\n",__FILE__, __FUNCTION__, __LINE__);
    }
    return sockfd;
}
Acceptor::Acceptor(EventLoop* loop, const InetAddress& listenAddr, bool reuseport)
: loop_(loop)
, acceptSocket_(createNonBlockingSocket())
, acceptChannel_(loop, acceptSocket_.fd())
, listenning_(false)
{
    acceptSocket_.setReuseAddr(true);
    acceptSocket_.setReusePort(true);
    acceptSocket_.bindAddress(listenAddr);

    acceptChannel_.setReadCallBack(std::bind(&Acceptor::handleRead, this));
    acceptChannel_.enableReading();
 }


// acceptChanel 所需的 read回调
void Acceptor::handleRead(){
    InetAddress peerAddr;
    int connfd = acceptSocket_.accept(&peerAddr);
    if(connfd >= 0){
        if(newConnectionCallBack_){
            // 调用connectionCallBack
            newConnectionCallBack_(connfd, peerAddr);
        }else{
            ::close(connfd);
        }
    }else{
        LOG_ERROR("%s:%s:%d accept error:%d \n", __FILE__, __FUNCTION__, __LINE__, errno);
    }
}

Acceptor::~Acceptor(){
    acceptChannel_.disableAll();
    acceptChannel_.remove();
}


void Acceptor::listen(){
    listenning_ = true;
    acceptSocket_.listen();
    acceptChannel_.enableReading();
}

